﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Xml.Linq;
using CodeContrib;
using CodeContrib.Web.Mvc;
using CodeContribBlog.Data;

namespace CodeContribBlog.Web.Mvc.Controllers
{
	public class SyndicationController : BlogController
	{
		//private static readonly string _eTagKey;

		//static SyndicationController()
		//{
		//	_eTagKey = Guid.NewGuid().ToString();
		//}

		public ActionResult CommentsRss(int? id /* postId */)
		{
			IEnumerable<Comment> comments = BlogContext.Comments;

			if (id != null)
			{
				comments = comments.Where(x => x.PostId == id);
			}

			comments = comments.ToList();

			var eTag = typeof (SyndicationController).FullName;

			//if (CheckEtag(stats, out eTag))
			//{
			//	return HttpNotModified();
			//}

			var rss = new XDocument(new XElement("rss", new XAttribute("version", "2.0"), new XElement("channel", new XElement("title", Blog.Title), new XElement("link", Url.RelativeToAbsolute(Url.RouteUrl("BlogHome"))), new XElement("description", Blog.MetaDescription ?? Blog.Title), new XElement("copyright", string.Format("{0} (c) {1}", Blog.Copyright, DateTime.Now.Year)), new XElement("ttl", "60"), comments.Select(c => new
				                                                                                                                                                                                                                                                                                                                                                                                                                              {
					                                                                                                                                                                                                                                                                                                                                                                                                                              Comment = c,
					                                                                                                                                                                                                                                                                                                                                                                                                                              CommentUrl = Url.AbsoluteRouteUrl("PostDetails", new
						                                                                                                                                                                                                                                                                                                                                                                                                                                                                               {
							                                                                                                                                                                                                                                                                                                                                                                                                                                                                               c.Post.Id,
							                                                                                                                                                                                                                                                                                                                                                                                                                                                                               c.Post.Slug,
							                                                                                                                                                                                                                                                                                                                                                                                                                                                                               c.Post.ShowIfPrivate
						                                                                                                                                                                                                                                                                                                                                                                                                                                                                               })
				                                                                                                                                                                                                                                                                                                                                                                                                                              }).Select(x => new XElement("item", new XElement("title", string.Format("{0} commented on {1}", x.Comment.Author, x.Comment.Post.Title), new XElement("description", x.Comment.Body), new XElement("link", x.CommentUrl), new XElement("guid", x.CommentUrl), new XElement("pubDate", x.Comment.CreatedAt.ToString("R"))))))));

			return new XmlResult(rss, eTag);
		}

		public ActionResult Rsd()
		{
			var @namespace = XNamespace.Get("http://archipelago.phrasewise.com/rsd");

			var eTag = typeof (SyndicationController).FullName;

			var rsd = new XDocument(new XElement(@namespace + "service", new XElement(@namespace + "engineName", Blog.Title), new XElement(@namespace + "engineLink", "http://codecontribblog.com"), new XElement(@namespace + "homePageLink", Blog.Url), new XElement(@namespace + "apis", new XElement(@namespace + "api", new XAttribute("name", "MetaWeblog"), new XAttribute("preferred", "true"), new XAttribute("blogID", "0"), new XAttribute("apiLink", string.Format("{0}/api/metaweblog.ashx", Blog.Url.RemoveTrailingCharacters("/")))))));

			return new XmlResult(rsd, eTag);
		}

		public ActionResult Rss(string tag)
		{
			IEnumerable<Post> posts = BlogContext.Posts
				.WhereIsPublic();

			if (!string.IsNullOrEmpty(tag))
			{
				posts = posts.Where(p => p.Tags
					                         .Select(t => t.Slug)
					                         .Contains(tag));
			}

			posts = posts.ToList();

			var eTag = typeof (SyndicationController).FullName;

			//if (CheckEtag(stats, out eTag))
			//{
			//	return HttpNotModified();
			//}

			var rss = new XDocument(
				new XElement("rss", new XAttribute("version", "2.0"),
				             new XElement("channel",
				                          new XElement("title", Blog.Title),
				                          new XElement("link", Url.RelativeToAbsolute(Url.RouteUrl("BlogHome"))),
				                          new XElement("description", Blog.MetaDescription ?? Blog.Title),
				                          new XElement("copyright", string.Format("{0} (c) {1}", Blog.Copyright, DateTime.Now.Year)),
				                          new XElement("ttl", "60"), posts.Select(p => new
					                                                                       {
						                                                                       Post = p,
						                                                                       PostUrl = Url.AbsoluteRouteUrl("PostDetails", new
							                                                                                                                     {
								                                                                                                                     p.Id,
								                                                                                                                     p.Slug,
								                                                                                                                     p.ShowIfPrivate
							                                                                                                                     })
					                                                                       }).Select(x => new XElement("item",
					                                                                                                   new XElement("title", x.Post.Title),
					                                                                                                   new XElement("description", x.Post.Body),
					                                                                                                   new XElement("link", x.PostUrl),
					                                                                                                   new XElement("guid", x.PostUrl),
					                                                                                                   new XElement("pubDate", x.Post.PublishedAt.ToString("R")))))));

			return new XmlResult(rss, eTag);
		}

		//private bool CheckEtag(DateTime timeStamp, out string responseETag)
		//{
		//	string requestETag = Request.Headers["If-None-Match"] ?? string.Empty;
		//	responseETag = timestamp.ToString("o") + _eTagKey;

		//	return (requestETag == responseETag);
		//}
	}
}